package com.collect.senegal.zhiScene.zhiLogin.zhiFace.zhiLivenessUtil;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.baidu.idl.face.platform.listener.IInitCallback;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.senegal.zhiUtils.SPUtils;

import java.util.ArrayList;
import java.util.List;

public class LivenessIntentUtil {

    public static final int REQUEST_CODE_FACE = 233;

    //判断曾经调起失败flag
    public static final String LIVENESS_EXCEPTION_FLAG = "LIVE_EXC_FLAG";

    public LivenessIntentUtil() {
        this.isLivenessRandom = true;

        this.mLivenessList = new ArrayList<>();
        this.mLivenessList.add(LivenessTypeEnum.Mouth);
        this.mLivenessList.add(LivenessTypeEnum.Eye);
        this.mLivenessList.add(LivenessTypeEnum.HeadLeft);
        this.mLivenessList.add(LivenessTypeEnum.HeadRight);
    }

    public static LivenessIntentUtil getInstance() {
        return instance;
    }

    private static final LivenessIntentUtil instance = new LivenessIntentUtil();

    //动作列表
    public List<LivenessTypeEnum> mLivenessList;

    //是否随机动作
    public boolean isLivenessRandom = true;

    //是否初始化成功
    private boolean hasGotToken = false;

    //是否检测成功
    public boolean isDetectSuccess = false;
    //检测成功为空字串，失败则是原因说明
    public String detectMsg = "";
    //如果检测成功，保存最佳图片的本地路径
    public String detectFilePath = "";
    //如果检测成功，保存最佳图片的bitmap
    public Bitmap detectFileImage = null;

    /**
     * 判断是否能调起ocr组件
     * 如果出现异常，则不调起ocr
     *
     * @type method
     * @author liwenjie
     * @creatTime 2020-07-20 11:23
     */
    public boolean checkCanStartLiveness() {
        if (hasGotToken) {
            String gFlag = SPUtils.getInstance().getString(LIVENESS_EXCEPTION_FLAG);
            if (TextUtils.isEmpty(gFlag)) {
                gFlag = "NO";
            }
            if (gFlag.equalsIgnoreCase("YES")) {
                return false;
            }
            return true;
        }

        return false;
    }

    /**
     * 设置调起ocr异常标志
     *
     * @type method
     * @author liwenjie
     * @creatTime 2020/8/5 11:00
     */
    public static void setLivenessRunException() {
        SPUtils.getInstance().put(LIVENESS_EXCEPTION_FLAG, "YES");
    }

    /**
     * 设置sdk配置参数
     *
     * @type method
     * @author liwenjie
     * @creatTime 2020/8/10 15:59
     */
    public void setFaceConfig() {
        try {
            FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();

            // SDK初始化已经设置完默认参数（推荐参数），您也根据实际需求进行数值调整
            config.setLivenessTypeList(this.mLivenessList);
            config.setLivenessRandom(this.isLivenessRandom);
            config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
            config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
//            config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE);
            config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
            config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL);
            config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
            config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
            config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
            config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
            config.setLivenessRandom(true);
            config.setSound(true);
//            config.setCheckFaceQuality(true);
//            config.setFaceDecodeNumberOfThreads(2);
            config.setCacheImageNum(1);

            ArrayList<LivenessTypeEnum> livenessTypeList = new ArrayList<>();
            livenessTypeList.add(LivenessTypeEnum.Mouth);
//            livenessTypeList.add(LivenessTypeEnum.Eye);
//            livenessTypeList.add(LivenessTypeEnum.HeadLeft);
//            livenessTypeList.add(LivenessTypeEnum.HeadRight);
            config.setLivenessTypeList(livenessTypeList);
            config.setTimeDetectModule(FaceEnvironment.TIME_DETECT_MODULE);
            config.setFaceFarRatio(FaceEnvironment.VALUE_FAR_RATIO);
            config.setFaceClosedRatio(FaceEnvironment.VALUE_CLOSED_RATIO);
            config.setSecType(FaceEnvironment.VALUE_SEC_TYPE);
            config.setScale(FaceEnvironment.VALUE_SCALE);
            config.setCropHeight(FaceEnvironment.VALUE_CROP_HEIGHT);
            config.setCropWidth(FaceEnvironment.VALUE_CROP_WIDTH);
            FaceSDKManager.getInstance().setFaceConfig(config);
        } catch (Exception e) {
            e.printStackTrace();
            setLivenessRunException();
        }
    }

    /**
     * 判断是否已经初始化
     *
     * @type method
     * @author liwenjie
     * @creatTime 2020-07-20 11:23
     */
    public boolean checkTokenStatus() {
        return hasGotToken;
    }

    /**
     * 初始化SDK
     */
    public void startFaceRecog(final Activity activity, final int reqCode) {
        // 为了android和ios 区分授权，appId=appname_face_android ,其中appname为申请sdk时的应用名
        // 应用上下文
        // 申请License取得的APPID
        // assets目录下License文件名
        hasGotToken = true;
        try {
            FaceSDKManager.getInstance().initialize(activity, ZHIProjectConfigs.BD_LIVENESS_LICENESE_ID, ZHIProjectConfigs.BD_LIVENESS_LICENESE_FILE_NAME, new IInitCallback() {
                @Override
                public void initSuccess() {
                    hasGotToken = true;
                    setFaceConfig();
                    openFaceRecogUI(activity, reqCode);
                }

                @Override
                public void initFailure(int i, String s) {
                    hasGotToken = false;
                }
            });
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void openFaceRecogUI(Activity activity, int reqCode) {
        if (!getInstance().checkTokenStatus()) {
            return;
        }
        try {
            Intent intent = new Intent(activity, FaceLivenessExpActivity.class);
            activity.startActivityForResult(intent, reqCode);
        } catch (Exception e) {
            e.printStackTrace();
            setLivenessRunException();
        }
    }
}
